import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestCase {
	private Candidate candidate;

	public TestCase(Candidate c) {
		this.candidate = c;
	}

	public Candidate getCandidate() {
		return candidate;
	}

	public void setCandidate(Candidate candidate) {
		this.candidate = candidate;
	}

	private static void printLines(InputStream ins) throws Exception {
		String line = null;
		BufferedReader in = new BufferedReader(new InputStreamReader(ins));
		while ((line = in.readLine()) != null) {
			System.out.println(line);
		}
	}

	private static void printLinesVerifyError(InputStream ins) throws Exception {
		String line = null;
		BufferedReader in = new BufferedReader(new InputStreamReader(ins));
		while ((line = in.readLine()) != null) {
			if (line.contains("INSTRUMENTATION_RESULT:")
					|| line.contains("Error in")
					|| line.contains("FAILURES!!!")) {
				throw new Exception("Failure occured");
			}
			System.out.println(line);
		}
	}

	private static void runProcess(String command) throws Exception {
		Process pro = Runtime.getRuntime().exec(command);
		printLinesVerifyError(pro.getInputStream());
		printLines(pro.getErrorStream());
		pro.waitFor();
		System.out.println("EXIT VALUE: " + pro.exitValue());
	}

	public boolean execute(String folderDest) {
		File f = new File("teste.txt");

		boolean ok = true;

		try {
			if (!f.exists()) {
				f.createNewFile();
			}

			FileWriter fw = new FileWriter(f.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);

			Event[] e = this.candidate.getEvents();

			for (int i = 0; i < Candidate.EVENT_LIST_SIZE; ++i) {
				bw.write(e[i].getCode() + "\n");
			}

			bw.close();
		} catch (IOException e) {
			System.err
					.println("Erro ao criar arquivo para executar caso de teste.");
			System.exit(1);
		}

		try {
			runProcess("adb push teste.txt data/local/tmp/teste.txt");
			//runProcess("adb shell am instrument -w com.ctntest/android.test.InstrumentationTestRunner");
			runProcess("adb shell am instrument -w com.calculator.test/android.test.InstrumentationTestRunner");
			runProcess("adb shell rm data/local/tmp/teste.txt");
		} catch (Exception e) {
			ok = false;
			// e.printStackTrace();
		}

		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
		Date date = new Date();
		String folder = folderDest + "/" + (ok ? "ok/" : "fail/");

		String testCaseName = folder + "test_" + dateFormat.format(date)
				+ ".in";

		File tc = new File(testCaseName);

		f.renameTo(tc);

		return ok;
	}
}
